<template>
  <div v-loading="loading" class="classify-con">
    <el-scrollbar class="classify-scrollbar">
      <div v-permission="permissionInsert" class="classify-add" @click="addClassify">+点击此处添分类</div>
      <div v-for="(item, index) in formatData" :key="index" class="classify-item">
        <div class="item-info">
          <el-input v-model.trim="item.title" :disabled="!item._edit" placeholder="请输入分类名称" style="width: 50%; margin-right: 10px;" />
          <el-radio-group v-model="item.status" :disabled="!item._edit">
            <el-radio v-for="(n, key) in dict.ZT" :key="key" :label="n.dictValue">{{ n.dictName }}</el-radio>
          </el-radio-group>
          <el-input v-model.trim="item.sort" :disabled="!item._edit" placeholder="排序" style="width: 20%;margin-left: 10px;" />
        </div>
        <div class="item-btn">
          <el-button v-permission="permissionUpdate" size="mini" type="text">
            <i v-if="item._edit" class="el-icon-success" @click="classifyUpdateSub(item, index)" />
            <i v-else class="el-icon-edit-outline" @click="classifyUpdate(item, index)" />
          </el-button>
          <el-button v-permission="permissionDelete" size="mini" type="text" @click="classifyDelete(item, index)">
            <i class="el-icon-delete" />
          </el-button>
        </div>
      </div>
    </el-scrollbar>
  </div>
</template>
<script>
import { getDictByCode, queryAll, insert, update, del } from './api'
import permission from '@/directive/permission/index.js' // 权限判断指令
import Vue from 'vue'
export default {
  name: 'Classify',
  directives: { permission },
  props: {
    type: {
      type: String,
      default: ''
    },
    parentref: {
      type: Boolean,
      default: false
    },
    permissionInsert: {
      type: String,
      default: ''
    },
    permissionUpdate: {
      type: String,
      default: ''
    },
    permissionDelete: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      loading: false,
      data: [],
      dict: {
        ZT: []
      }
    }
  },
  computed: {
    formatData() {
      let tmp
      if (!Array.isArray(this.data)) {
        tmp = [this.data]
      } else {
        tmp = this.data
      }
      Array.from(tmp).forEach(item => {
        if (item._edit === undefined) {
          Vue.set(item, '_edit', false)
        }
      })
      return tmp
    }
  },
  created() {
    for (const key in this.dict) {
      this.getDict(key)
    }
    this.queryClassify()
  },
  methods: {
    /**
     * 获取字典
     */
    getDict(code) {
      return new Promise((resolve, reject) => {
        getDictByCode(code).then(res => {
          this.dict[code] = (res.data.data && res.data.data.length > 0) ? res.data.data[0].list : []
        }).catch(error => {
          reject(error)
        })
      })
    },

    /**
     * 切换编辑状态
     */
    toggleEdit(index) {
      const record = this.formatData[index]
      record._edit = !record._edit
    },

    /**
     * 查询分类列表
     */
    queryClassify() {
      this.loading = true
      return new Promise((resolve, reject) => {
        queryAll({ type: this.type }).then(response => {
          this.data = response.data.data
          this.loading = false
        }).catch(error => {
          reject(error)
        })
      })
    },

    /**
     * 添加
     */
    addClassify() {
      this.temp = {
        id: '',
        title: '',
        status: 'ZT01',
        sort: '',
        _edit: true
      }
      this.data.unshift(this.temp)
    },

    /**
     * 编辑
     */
    classifyUpdate(item, index) {
      this.toggleEdit(index)
    },

    /**
     * 编辑提交
     */
    classifyUpdateSub(item, index) {
      if (item.title.trim() !== '') {
        item['type'] = this.type
        this.loading = true
        return new Promise((resolve, reject) => {
          if (item.id === '') {
            insert(item).then(() => {
              this.loading = false
              this.$message({
                title: '成功',
                message: '添加成功',
                type: 'success',
                duration: 2000
              })
              this.refresh()
            }).catch(error => {
              this.loading = false
              reject(error)
            })
          } else {
            update(item).then(() => {
              this.loading = false
              this.$message({
                title: '成功',
                message: '编辑成功',
                type: 'success',
                duration: 2000
              })
              this.refresh()
            }).catch(error => {
              this.loading = false
              reject(error)
            })
          }
        })
      } else {
        this.$message({
          message: '请输入分类名称',
          type: 'warning'
        })
      }
    },

    /**
     * 删除
     */
    classifyDelete(item, index) {
      this.$confirm('此操作将永久删除该分类, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (item.id && item.id !== '') {
          this.deleteclassify(item.id)
        } else {
          this.data.splice(index, 1)
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },

    /**
     * 删除提交
     */
    deleteclassify(ids) {
      this.loading = true
      return new Promise((resolve, reject) => {
        del(ids).then(() => {
          this.loading = false
          this.$message({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          this.refresh()
        }).catch(error => {
          this.loading = false
          reject(error)
        })
      })
    },

    /**
     * 更新
     */
    refresh() {
      this.queryClassify()
      if (this.parentref) {
        this.$emit('onrefresh')
      }
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">
.classify-con {
  position: relative;
  .classify-scrollbar {
    width: 100%;
    height: 100%;
    overflow: hidden;
    .el-scrollbar__wrap {
      max-height: 400px;
      margin-bottom: 0 !important;
      overflow-x: hidden;
    }
    .el-scrollbar__view {
      margin: 10px;
      overflow: hidden;
    }
  }
  .classify-add {
    height: 40px;
    line-height: 40px;
    border: 1px dotted rgba(226, 227, 232, 1);
    border-radius: 4px;
    font-size: 14px;
    font-family: PingFangSC-Regular;
    font-weight: 400;
    color: rgba(254, 90, 97, 1);
    text-align: center;
    cursor: pointer;
    margin-bottom: 10px;
    &:hover {
      border: 1px dotted #fe5a61;
    }
  }
  .classify-item {
    width: 100%;
    display: flex;
    align-items: center;
    margin-top: 10px;

    .item-info {
      flex: 1;
      display: flex;
      align-items: center;
      .sort {
        margin-left: 20px;
        color: #c0c4cc;
        display: inline-block;
        font-size: 14px;
        vertical-align: baseline;
        width: 15%;
        text-align: center;
      }
    }
    .item-btn {
      margin-left: 20px;
    }
  }
}
</style>
